<?php
/**
 * Class Order
 * Desc  订单控制器
 * Create on 2022/10/12 9:16
 * Create by wangyafang
 */

namespace app\api\controller\wdsxh\mall;

use addons\wdsxh\library\Wxapp;
use app\admin\model\wdsxh\mall\Freight;
use app\admin\model\wdsxh\mall\Goods;
use app\admin\model\wdsxh\mall\Logistics;
use app\admin\model\wdsxh\mult\Store;
use app\api\model\wdsxh\mall\Cart;
use app\api\model\wdsxh\mall\OrderItem;
use app\common\controller\Api;
use app\common\model\Hospital;
use app\common\model\OrderLog;
use think\Db;
use think\Exception;
use think\Log;

class Order extends Api
{
    protected $noNeedLogin = ['payResult','show_postage','splitOrder','splitOrderItemData'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $model = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = (new \app\api\model\wdsxh\mall\Order());
    }

    //创建订单
    //param:token  buy_now:是否为立即购买:1立即购买;2购物车购买  address_id
    //立即购买：token buy_now goods_id  goods_num
    //购物车购买：token buy_now cart_ids
    public function create()
    {
        $user_id = $this->auth->id;
        $param = $this->request->param();
        $buy_now = $param['buy_now'];
        if (empty($buy_now)) {
            $this->error('参数不正确');
        }
        $userAddressObj = (new \app\api\model\wdsxh\mall\Address())
            ->where('id',$param['address_id'])
            ->field('name,tel,province,city,area,address')
            ->find();
        $order_no = wdsxh_create_order();
        $createCommonData = [
            'order_no'=>$order_no,
            'user_id'=>$user_id,
            'real_name'=>$userAddressObj['name'],
            'user_phone'=>$userAddressObj['tel'],
            'user_address'=>$userAddressObj['province'].$userAddressObj['city'].$userAddressObj['area'].$userAddressObj['address'],
        ];
        switch ($buy_now) {
            case 1://立即购买token buy_now goods_id  goods_num
                $goodsObj = (new Goods())->where('id',$param['goods_id'])->field('price,source,store_id,member_unit_id')->find();
                $cart_insert_data = [
                    [
                        'type'=>'1',//平台
                        'user_id'=>$user_id,
                        'goods_id'=>$param['goods_id'],
                        'goods_num'=>1,
                        'buy_now'=>'1',//是否为立即购买:1立即购买;
                        'store_id'=>-1,
                        'deletetime'=>time(),
                    ],
                ];
                $pay_postage = $this->postage([
                    [
                        'store_id'=>$goodsObj['store_id'],
                        'goods_id'=>$param['goods_id'],
                        'total_price'=>$goodsObj['price'] * $cart_insert_data[0]['goods_num'],
                    ]
                ]);
                $total_num = 1;
                $goods_total_price = $goodsObj['price'] * $total_num;
                $total_price = $goods_total_price + $pay_postage;
                $pay_price = $total_price;
                $order_insert_data = [
                    'buy_now'=>'1',//是否为立即购买:1立即购买;
                    'total_num'=>$total_num,//订单商品总数
                    'total_price'=> $total_price,
                    'pay_price'=>$pay_price,
                    'pay_postage'=>$pay_postage,
                    'source'=>$goodsObj['source'],
                    'store_id'=>$goodsObj['store_id'],
                    'member_unit_id'=>$goodsObj['member_unit_id'],
                    'goods_total_price'=>$goods_total_price,
                ];
                break;
            case 2://购物车购买
                //购物车购买：token buy_now cart_ids
                $goodsModel = new Goods();
                $cartModel = new \app\api\model\wdsxh\mall\Cart();
                $cart_ids_array = explode(',',$param['cart_ids']);
                $cartWhere['cart.id'] = array('in',$cart_ids_array);
                $cartStoreIdArray = $cartModel->alias('cart')
                    ->where($cartWhere)
                    ->field('store_id,goods_id,goods_num')
                    ->select();
                $postageParam = [];
                foreach ($cartStoreIdArray as $k=>$v) {
                    $postageParam[$k]['store_id'] = $v['store_id'];
                    $postageParam[$k]['goods_id'] = $v['goods_id'];
                    $postageParam[$k]['total_price'] = $goodsModel->where('id',$v['goods_id'])->value('price') * $v['goods_num'];
                }
                $store_count = count(array_unique(array_column(collection($cartStoreIdArray)->toArray(), 'store_id')));
                $cart_insert_data = [];
                foreach ($cart_ids_array as $v) {
                    $cart_insert_data[] = [
                        'id'=>$v,//平台
                        'deletetime'=>time(),
                    ];
                }
                $pay_postage = $this->postage($postageParam);
                $cartObj = $cartModel
                    ->alias('cart')
                    ->where($cartWhere)
                    ->join('wdsxh_mall_goods goods','goods.id = cart.goods_id')
                    ->field('sum(goods_num) total_num,sum(cart.goods_num * goods.price) goods_total_price')
                    ->find();
                $total_num = $cartObj['total_num'];
                $total_price = $cartObj['goods_total_price'] + $pay_postage;
                $pay_price = $total_price;
                $order_insert_data = [
                    'buy_now'=>'2',//是否为立即购买:1购物车购买;
                    'total_num'=>$total_num,//订单商品总数
                    'total_price'=> $total_price,
                    'pay_price'=>$pay_price,
                    'pay_postage'=>$pay_postage,
                    'cart_ids'=>$param['cart_ids'],
                    'goods_total_price'=>$cartObj['goods_total_price'],
                ];
                if($store_count > 1) {
                    $order_insert_data['admin_show'] = 2;
                }
                break;
        }
        $order_insert_data = array_merge($order_insert_data,$createCommonData);
        Db::startTrans();
        try {
            $cartObjList = (new \app\api\model\wdsxh\mall\Cart())->saveAll($cart_insert_data);
            if($buy_now == 1) {
                $cartArrayList = collection($cartObjList)->toArray();
                $order_insert_data['cart_ids'] = $cartArrayList[0]['id'];
            }
            $this->model->save($order_insert_data);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交订单成功',['id'=>$this->model->id,'order_no'=>$this->model->order_no]);
    }

    //微信预支付
    //param:token id
    public function prepare_pay()
    {
        $id = $this->request->get('id');
        $openid = wdsxh_get_openid($this->auth->id);
        $orderObj = $this->model
            ->where('id',$id)
            ->field('order_no,pay_price')
            ->find();
        $data = [];
        try{
            $data=\addons\wdsxh\library\Wxapp::unify('商城商品购买',$orderObj->order_no,$orderObj->pay_price,$openid,request()->domain().'/api/wdsxh/mall/order/payresult');
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('success',$data);
    }
    /*
     * (单商城)多店铺订单支付处理
     */
    public function payResult(){
        $pay=Wxapp::getPay();
        $response = $pay->handlePaidNotify(function($message, $fail){
            Log::record('测试日志信息,这是警告级别，并且实时写入','log');
//        $message['out_trade_no'] = '202309151051160370';
            Log::record($message['out_trade_no'],'logeuas');
       $order =$this->model->where('order_no',$message['out_trade_no'])->find();
        if (!$order || $order->status == '1') {
            return true;
        }
        $orderItemModel = new OrderItem();
        if ($order->buy_now == '1') {//立即购买
            $orderArray = $order->toArray();
            Db::startTrans();
            try {
                $order->pay_time = time();
                $order->status = '1';
                $order->paid = '1';
                $order->save();
                $orderItemModel->saveAll($this->splitOrderItemData([$orderArray]));
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else{//购物车购买
            $splitResult = $this->splitOrder($this->model->get($order->id));
            if ($splitResult['code'] == 1) {
                Log::record($splitResult['code'],'logeipouas');
                $this->success();
                return true;
            } else {
                $order->status = '6';
                $order->split_fail_reason = $splitResult['msg'];
                $order->save();
            }
        }
        $this->success();
        return true;
        });
        $response->send();
    }


    //有订单数据拆分订单明细数据
    private function splitOrderItemData($orderData = [])
    {
        $goodsModel = new Goods();
        $itemMultData = [];
        foreach ($orderData as $k=>$v) {
            $cart_ids_array = explode(',',$v['cart_ids']);
            foreach ($cart_ids_array as $kk=>$vv) {
                $cartArray = Db::name('wdsxh_mall_cart')
                    ->where('id',$vv)
                    ->field('goods_id,goods_num')
                    ->find();
                $goodsObj = $goodsModel->where('id',$cartArray['goods_id'])
                    ->field('name,image,price,unit')
                    ->find();
                $itemMultData[] = [
                    'order_id'=>$v['id'],
                    'goods_id'=>$cartArray['goods_id'],
                    'goods_num'=>$cartArray['goods_num'],
                    'goods_name'=>$goodsObj['name'],
                    'goods_image'=>$goodsObj['image'],
                    'goods_price'=>$goodsObj['price'],
                    'unit'=>$goodsObj['unit'],
                    'pay_price'=>$goodsObj['price'] * $cartArray['goods_num'],
                ];
                unset($cartArray);
                unset($goodsObj);
            }
        }
        return $itemMultData;

    }

    //购物车订单,支付订单成功后拆分订单
    private function splitOrder($orderObj = [])
    {
        Log::record($orderObj,'logeopas');
        $storeModel = new Store();
        $orderItemModel = new OrderItem();
        $cart_ids_array = explode(',',$orderObj['cart_ids']);
        $cartData = \app\api\model\wdsxh\mall\Cart::onlyTrashed()->where('id', 'in', $cart_ids_array)->field('id,store_id')->select();
        $cartData = collection($cartData)->toArray();
        $store_id_array = array_unique(array_column($cartData,'store_id'));
        $splitData = [];
        foreach ($store_id_array as $k=>$v) {
            $splitData[$k]['store_id'] = $v;
            $splitData[$k]['cart_ids'] = $this->returnCartIdsArray($v,$cartData);
        }
        $createCommonData = [
            'parent_id'=>$orderObj->id,
            'buy_now'=>$orderObj->buy_now,
            'user_id'=>$orderObj->user_id,
            'real_name'=>$orderObj->real_name,
            'user_phone'=>$orderObj->user_phone,
            'user_address'=>$orderObj->user_address,
            'status'=>1,
            'paid'=>$orderObj->paid,
            'pay_time'=>$orderObj->pay_time,
        ];
        $order_insert_data = [];
        foreach ($splitData as $v) {
            $cartWhere['cart.id'] = array('in',$v['cart_ids']);
            $v['cart_ids'] = implode(',',$v['cart_ids']);
            $tem = array_merge($v,$createCommonData);
            $goodsModel = new Goods();
            $cartStoreIdArray = \app\api\model\wdsxh\mall\Cart::onlyTrashed()->alias('cart')
                ->where($cartWhere)
                ->field('store_id,goods_id,goods_num')
                ->select();
            $postageParam = [];
            foreach ($cartStoreIdArray as $k=>$v) {
                if($v['store_id'] == -1) {
                    $tem['source'] = 1;
                } else{
                    $tem['source'] = 2;
                }
                $postageParam[$k]['store_id'] = $v['store_id'];
                $tem['member_unit_id'] = $storeModel->where('id',$v['store_id'])->value('member_unit_id');
                $postageParam[$k]['goods_id'] = $v['goods_id'];
                $postageParam[$k]['total_price'] = $goodsModel->where('id',$v['goods_id'])->value('price') * $v['goods_num'];
            }
            $tem['pay_postage'] = $this->postage($postageParam);
            $tem['total_num'] = \app\api\model\wdsxh\mall\Cart::onlyTrashed()->alias('cart')->where($cartWhere)->sum('goods_num');
            $tem['goods_total_price'] = \app\api\model\wdsxh\mall\Cart::onlyTrashed()->alias('cart')->where($cartWhere)
                ->join('wdsxh_mall_goods goods','goods.id = cart.goods_id')
                ->sum('goods.price');
            $tem['total_price'] = $tem['goods_total_price'] + $tem['pay_postage'];
            $tem['pay_price'] = $tem['total_price'];
            $tem['order_no'] = $orderObj['order_no'];
            $tem['member_unit_id'] = -1;
            $tem['paid'] = 1;

            $order_insert_data[] = $tem;
            Log::record($order_insert_data,'order_insert_data');
        }
        $msg_array = [];

        Db::startTrans();
        try {
            (new \app\api\model\wdsxh\mall\Order())->where('order_no',$orderObj['order_no'])->update(['order_no'=>$orderObj['order_no'].'1']);
            $orderObj->delete();
            $newOrderObj = (new \app\api\model\wdsxh\mall\Order())->allowField(true)->saveAll($order_insert_data);
            Log::record($newOrderObj,'newOrderObj');
            $orderItemModel->allowField(true)->saveAll($this->splitOrderItemData(collection($newOrderObj)->toArray()));
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $msg_array = [
                'code'=>0,
                'msg'=>$e->getMessage(),
            ];
        }
        if($newOrderObj) {
            return [
                'code'=>1,
                'msg'=>'ok',
            ];
        } else {
            return $msg_array;
        }
    }

    private function returnCartIdsArray($store_id,$array)
    {
        $cartIdsArray = [];
        foreach ($array as $v) {
            if($store_id == $v['store_id']) {
                $cartIdsArray[] = $v['id'];
            }
        }
        return $cartIdsArray;

    }

    //订单列表
    //param:token status
    public function list()
    {
        $user_id = $this->auth->id;
        $where['user_id'] = array('eq',$user_id);
        $page = $this->request->get('page','');
        $limit = $this->request->get('limit',10);
        $param = $this->request->param();
        $refund_status = $this->request->get('refund_status','');
        if (isset($param['status'])) {
            $where['status'] = array('eq',$param['status']);
        }
        if ($refund_status) {
            $where['refund_status'] = array('eq',$refund_status);
        }
        if(!$refund_status) {
            $field = 'id,order_no,status,pay_price,cart_ids,pay_price,total_num,refund_status';
        } else {
            $field = 'id,order_no,status,pay_price,cart_ids,pay_price,total_num,refund_status';
        }
        $count = $this->model
            ->where($where)
            ->count();
        $data = $this->model
            ->where($where)
            ->page($page,$limit)
            ->order('id desc')
            ->field($field)
            ->select();
        foreach ($data as &$v) {
            $v->append(['goods']);
            if ($v['status'] == -1){
                $refundModel = (new \app\admin\model\wdsxh\mall\Refund())->where('order_id',$v['id'])->find();
                if ($refundModel){
                    $v->numbers_status = 1;
                }else{
                    $v->numbers_status = 0;
                }
            }
        }

        $this->success('请求成功',['count'=>$count,'data'=>$data]);

    }

    //订单统计
    //param:token status
    public function order_count()
    {
        $user_id = $this->auth->id;
        $where['user_id'] = array('eq',$user_id);
        $whole = $this->model->where($where)->count();
        $obligation = $this->model->where($where)->where('status','0')->count();
        $take_over = $this->model->where($where)->where('status','2')->count();
        $refund = $this->model->where($where)->where('status','-1')->count();
        $data = [
            'whole'=>$whole,//全部
            'obligation'=>$obligation,//待付款
            'take_over'=>$take_over,//待收货
            'refund'=>$refund,//退款
        ];
        $this->success('请求成功',$data);
    }

    public function pay_order_detail(){
        $param = $this->request->param();
        $user_id = $this->auth->id;
        $data = Db::name('wdsxh_mall_order')
            ->where('user_id',$user_id)
            ->where('id',$param['order_id'])
            ->field('id,parent_id,status')->find();
        if ($data['status'] == 1){
            $data['order_id'] = $data['id'];
        }else{
            $order_id = Db::name('wdsxh_mall_order')
                ->where('user_id',$user_id)
                ->where('parent_id',$data['id'])
                ->where('status',1)
                ->field('id,parent_id')->find();
            $data['order_id'] = $order_id['id'];
        }
        $this->success('请求成功',$data);

    }

    //详情
    //param:token 订单id
    public function detail()
    {
        $id = $this->request->get('id');
        $orderObj = $this->model->where('id',$id)
            ->field('id,user_address,real_name,user_phone,cart_ids,status')
            ->find()->toArray();
        $refundModel = (new \app\admin\model\wdsxh\mall\Refund())->where('order_id',$orderObj['id'])->find();
        if ($refundModel){
            $orderObj['refund_reason'] = $refundModel['refund_reason'];
        }else{
            $orderObj['refund_reason'] = '';
        }
        $data['address'] = $orderObj;
        $cart_ids_array = explode(',',$orderObj['cart_ids']);
        $cartWhere['cart.id'] = array('in',$cart_ids_array);
        $orderInfo = Cart::onlyTrashed()
            ->alias('cart')
            ->where($cartWhere)
            ->order('cart.createtime desc,cart.id desc')
            ->join('wdsxh_mall_goods goods','goods.id = cart.goods_id')
            ->join('wdsxh_mult_store store','cart.store_id = store.id','left')
            ->field('cart.id cart_id,cart.goods_id,cart.goods_num,cart.store_id,
            goods.name goods_name,goods.image goods_image,goods.price goods_price,
            store.name store_name,store.image store_image')
            ->select();
        $orderInfo=collection($orderInfo)->toArray();
        $orderInfo = (new \app\api\controller\wdsxh\mall\Cart())->splitCartData($orderInfo);
        foreach ($orderInfo as $k=>$v) {
            $postageParam = [];
            foreach ($v['child'] as $kk=>$vv) {//二维数组[['store_id'=>1,'goods_id'=>1,'total_price'=>1]]
                $postageParam[$kk]['store_id'] = $v['store_id'];
                $postageParam[$kk]['goods_id'] = $vv['goods_id'];
                $postageParam[$kk]['total_price'] = $vv['goods_price'] * $vv['goods_num'];
            }
            $orderInfo[$k]['postage'] = $this->postage($postageParam);
        }
        $data['orderInfo'] = $orderInfo;
        unset($data['address']['cart_ids']);
        $this->success('请求成功',$data);

    }

    //确认收货
    //param:token id
    public function sign()
    {
        $param = $this->request->param();
        Db::startTrans();
        try{
            $this->model->allowField(true)
                ->where('id',$param['id'])
                ->update([
                    'status' => 4,
                    'complete_time'=>time(),
                ]);
            (new Logistics())->allowField(true)
                ->where('order_id',$param['id'])
                ->update([
                    'receive_time' => time(),
                ]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('确认收货成功');
    }

    //计算邮费
    private function postage($params = [])//二维数组[['store_id'=>1,'goods_id'=>1,'total_price'=>1]]
    {
        $store_id_array = array_unique(array_column($params, 'store_id'));
        $freightModel = new Freight();
        $freightWhere['status'] = array('eq','normal');
        $total_price = 0;
        foreach ($store_id_array as $v) {
            $result = 0;
            $child_total_price = 0;
            $freightWhere['store_id'] = array('eq',$v);
            $single_total_price = 0;
            foreach ($params as $kk=>$vv) {
                if($v == $vv['store_id']) {
                    $single_total_price = $single_total_price + $vv['total_price'];
                }
            }
            $freightWhere['min'] = array('elt',$single_total_price);
            $freightWhere['max'] = array('egt',$single_total_price);
            $price = $freightModel->where($freightWhere)->value('price');
            if($price) {
                $result = $result + $price;
            } else {
                $result = $result + 10;
            }
            $child_total_price = $child_total_price + $result;
            $total_price = $total_price + $child_total_price;
            unset($result);
            unset($child_total_price);
        }

        return $total_price;
    }

    //显示邮费
    public function show_postage()
    {

        $param_json = $_GET['param_json'];
        $param = json_decode($param_json,true);
        $array = [];
        $goodsModel = new Goods;
        foreach ($param as $k=>$v) {
            $goodsObj = $goodsModel->where('id',$v['goods_id'])->field('store_id,price')->find();
            $array[] = [
                'store_id'=>$goodsObj['store_id'],
                'goods_id'=>$v['goods_id'],
                'total_price'=>$goodsObj['price'] * $v['goods_num'],
            ];
            unset($goodsObj);
        }
        $postage = $this->postage($array);
        $this->success('请求成功',['postage'=>$postage]);
    }

}



 